using UnityEngine;
using System.Collections.Generic;

[System.Serializable]
public class ExpressionData
{
    public string name;
    public List<BlendShapeSetting> blendShapes = new List<BlendShapeSetting>();
    
    [Header("眼睛设置")]
    public Texture eyeTexture;
    public bool useCustomEyeMaterial = false;  // 是否使用自定义眼睛材质（圈圈眼）
    public Material customEyeMaterial;         // 自定义眼睛材质
    [Range(0f, 1f)]
    public float eyeEffectWeight = 1f;         // 眼睛效果混合权重
    
    [Header("印堂发黑设置")]
    public bool enableForeheadShadow = false;  // 是否启用印堂发黑
    public Color foreheadShadowColor = new Color(0, 0, 0, 0.5f); // 阴影颜色
    [Range(0.4f, 0.9f)]
    public float foreheadShadowPosition = 0.6f; // 阴影在面部的位置
    [Range(0.01f, 0.2f)]
    public float foreheadShadowSize = 0.08f;    // 阴影大小
    [Range(0f, 1f)]
    public float foreheadShadowBlend = 0.7f;    // 阴影混合强度

    [Header("圈圈眼旋转设置")]
    public bool enableEyeRotation = false;     // 是否启用眼睛旋转
    [Range(0f, 360f)]
    public float rotationAngle = 0f;           // 初始旋转角度
    [Range(-10f, 10f)]
    public float rotationSpeed = 2f;           // 旋转速度，正值顺时针，负值逆时针
    public Vector2 rotationCenter = new Vector2(0.5f, 0.5f); // 旋转中心
}

[System.Serializable]
public class BlendShapeSetting
{
    public int blendShapeIndex;
    public float weight;
}

public class ExpressionManager : MonoBehaviour
{
    [Header("BlendShape控制")]
    public SkinnedMeshRenderer faceRenderer;
    
    [Header("材质设置")]
    public Material faceMaterial;  // 面部材质（用于印堂发黑）
    public Material eyeMaterial;   // 眼睛材质
    public string eyeTextureProperty = "_BaseMap";

    [Header("表情列表")]
    public List<ExpressionData> expressions = new List<ExpressionData>();

    [Header("过渡设置")]
    [Range(1f, 10f)]
    public float transitionSpeed = 5f; // 过渡速度，越大越快

    private int currentIndex = -1;
    private Dictionary<int, float> defaultBlendShapeWeights = new Dictionary<int, float>();
    private Texture defaultEyeTexture;
    private Material defaultEyeMaterial;

    // 过渡相关
    private Dictionary<int, float> targetWeights = new Dictionary<int, float>();
    private Texture targetEyeTexture;
    private bool isTransitioning = false;

    void Start()
    {
        // 记录初始BlendShape权重
        if (faceRenderer != null)
        {
            var mesh = faceRenderer.sharedMesh;
            for (int i = 0; i < mesh.blendShapeCount; i++)
            {
                defaultBlendShapeWeights[i] = faceRenderer.GetBlendShapeWeight(i);
            }
        }
        
        // 记录初始眼睛材质和贴图
        if (eyeMaterial != null)
        {
            defaultEyeMaterial = eyeMaterial;
            defaultEyeTexture = eyeMaterial.GetTexture(eyeTextureProperty);
        }

        // 初始化目标权重为当前权重
        ResetTargetWeightsToCurrent();
    }

    void Update()
    {
        if (faceRenderer == null) return;

        bool anyChanging = false;
        var mesh = faceRenderer.sharedMesh;
        for (int i = 0; i < mesh.blendShapeCount; i++)
        {
            float current = faceRenderer.GetBlendShapeWeight(i);
            float target = targetWeights.ContainsKey(i) ? targetWeights[i] : 0f;
            if (Mathf.Abs(current - target) > 0.01f)
            {
                float newValue = Mathf.Lerp(current, target, Time.deltaTime * transitionSpeed);
                faceRenderer.SetBlendShapeWeight(i, newValue);
                anyChanging = true;
            }
        }

        // 眼睛贴图切换（可选：渐变，可直接切换）
        if (eyeMaterial != null && targetEyeTexture != null && eyeMaterial.GetTexture(eyeTextureProperty) != targetEyeTexture)
        {
            // 这里直接切换，如需渐变可用shader实现
            eyeMaterial.SetTexture(eyeTextureProperty, targetEyeTexture);
        }

        isTransitioning = anyChanging;
    }

    public void ApplyExpression(int index)
    {
        if (index < 0 || index >= expressions.Count) return;

        var exp = expressions[index];

        // 设置目标BlendShape权重
        targetWeights.Clear();
        foreach (var bs in exp.blendShapes)
        {
            if (bs.blendShapeIndex >= 0 && bs.blendShapeIndex < faceRenderer.sharedMesh.blendShapeCount)
                targetWeights[bs.blendShapeIndex] = bs.weight;
        }
        
        // 其它BlendShape目标为0
        var mesh = faceRenderer.sharedMesh;
        for (int i = 0; i < mesh.blendShapeCount; i++)
        {
            if (!targetWeights.ContainsKey(i))
                targetWeights[i] = 0f;
        }

        // 处理眼睛材质/贴图 (圈圈眼功能)
        if (exp.useCustomEyeMaterial && exp.customEyeMaterial != null)
        {
            // 完全替换眼睛材质（圈圈眼情况）
            Material originalMaterial = eyeMaterial;
            eyeMaterial = exp.customEyeMaterial;
            targetEyeTexture = null; // 使用材质替换模式时不需要设置贴图
            
            // 如果有渲染器引用了这个材质，更新渲染器
            UpdateEyeMaterialReferences(originalMaterial, eyeMaterial);
            
            Debug.Log($"已切换至自定义眼睛材质: {eyeMaterial.name}, 权重: {exp.eyeEffectWeight}");
            
            // 设置混合权重（如果材质支持）
            if (eyeMaterial.HasProperty("_EffectBlend"))
            {
                eyeMaterial.SetFloat("_EffectBlend", exp.eyeEffectWeight);
            }
        }
        else
        {
            // 使用常规贴图替换模式
            targetEyeTexture = exp.eyeTexture != null ? exp.eyeTexture : defaultEyeTexture;
            
            // 立即切换贴图
            if (eyeMaterial != null && targetEyeTexture != null)
            {
                eyeMaterial.SetTexture(eyeTextureProperty, targetEyeTexture);
                Debug.Log($"已切换眼睛贴图: {targetEyeTexture.name}");
                
                // 如果原来用的是自定义材质，恢复默认材质
                if (eyeMaterial != defaultEyeMaterial)
                {
                    eyeMaterial = defaultEyeMaterial;
                    UpdateEyeMaterialReferences(eyeMaterial, defaultEyeMaterial);
                }
            }
        }

        // 处理印堂发黑
        if (faceMaterial != null)
        {
            // 设置印堂发黑开关
            if (exp.enableForeheadShadow)
            {
                faceMaterial.EnableKeyword("_USE_FOREHEAD_SHADOW");
                // 设置印堂发黑相关参数
                faceMaterial.SetColor("_ForheadShadowColor", exp.foreheadShadowColor);
                faceMaterial.SetFloat("_ForheadShadowPosition", exp.foreheadShadowPosition);
                faceMaterial.SetFloat("_ForheadShadowSize", exp.foreheadShadowSize);
                faceMaterial.SetFloat("_ForheadShadowBlend", exp.foreheadShadowBlend);
                
                Debug.Log($"已启用印堂发黑效果，位置: {exp.foreheadShadowPosition}, 大小: {exp.foreheadShadowSize}");
            }
            else
            {
                faceMaterial.DisableKeyword("_USE_FOREHEAD_SHADOW");
            }
        }

        // 处理圈圈眼旋转
        if (eyeMaterial != null)
        {
            if (exp.enableEyeRotation)
            {
                eyeMaterial.EnableKeyword("_USE_CIRCLE_ROTATION");
                eyeMaterial.SetFloat("_RotationAngle", exp.rotationAngle);
                eyeMaterial.SetFloat("_RotationSpeed", exp.rotationSpeed);
                eyeMaterial.SetVector("_RotationCenter", exp.rotationCenter);
                Debug.Log($"已启用眼睛旋转效果，角度: {exp.rotationAngle}°, 速度: {exp.rotationSpeed}");
            }
            else
            {
                eyeMaterial.DisableKeyword("_USE_CIRCLE_ROTATION");
            }
        }

        currentIndex = index;
        isTransitioning = true;
    }

    public void ResetExpression()
    {
        // BlendShape目标权重还原
        targetWeights.Clear();
        var mesh = faceRenderer.sharedMesh;
        for (int i = 0; i < mesh.blendShapeCount; i++)
        {
            float w = defaultBlendShapeWeights.TryGetValue(i, out float val) ? val : 0f;
            targetWeights[i] = w;
        }
        
        // 眼睛贴图还原
        targetEyeTexture = defaultEyeTexture;
        
        // 如果当前不是默认眼睛材质，恢复默认材质
        if (eyeMaterial != defaultEyeMaterial)
        {
            Material originalMaterial = eyeMaterial;
            eyeMaterial = defaultEyeMaterial;
            UpdateEyeMaterialReferences(originalMaterial, defaultEyeMaterial);
        }
        
        // 禁用印堂发黑
        if (faceMaterial != null)
        {
            faceMaterial.DisableKeyword("_USE_FOREHEAD_SHADOW");
        }

        // 禁用眼睛旋转
        if (eyeMaterial != null)
        {
            eyeMaterial.DisableKeyword("_USE_CIRCLE_ROTATION");
        }

        currentIndex = -1;
        isTransitioning = true;
    }

    private void ResetTargetWeightsToCurrent()
    {
        targetWeights.Clear();
        if (faceRenderer != null)
        {
            var mesh = faceRenderer.sharedMesh;
            for (int i = 0; i < mesh.blendShapeCount; i++)
            {
                targetWeights[i] = faceRenderer.GetBlendShapeWeight(i);
            }
        }
        targetEyeTexture = eyeMaterial != null ? eyeMaterial.GetTexture(eyeTextureProperty) : null;
    }
    
    // 辅助方法：更新场景中引用了旧眼睛材质的渲染器
    private void UpdateEyeMaterialReferences(Material oldMaterial, Material newMaterial)
    {
        if (oldMaterial == null || newMaterial == null) return;
        
        // 查找可能使用此眼睛材质的渲染器
        Renderer[] renderers = FindObjectsOfType<Renderer>();
        foreach (var renderer in renderers)
        {
            Material[] materials = renderer.sharedMaterials;
            bool materialChanged = false;
            
            for (int i = 0; i < materials.Length; i++)
            {
                if (materials[i] == oldMaterial)
                {
                    materials[i] = newMaterial;
                    materialChanged = true;
                }
            }
            
            if (materialChanged)
            {
                renderer.sharedMaterials = materials;
                Debug.Log($"已在对象 {renderer.gameObject.name} 上更新眼睛材质");
            }
        }
    }
    
    // 获取当前表情索引
    public int GetCurrentExpressionIndex()
    {
        return currentIndex;
    }
    
    // 检查是否正在过渡中
    public bool IsTransitioning()
    {
        return isTransitioning;
    }
}